﻿using AdminFrame.Enum;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;

namespace AdminFrame.Domain.Parameters
{
    public class ParameterManager : DomainService, IParameterManager
    {
        private readonly IParameterRepository _parameterRepository;

        public ParameterManager(IParameterRepository parameterRepository)
        {
            _parameterRepository = parameterRepository;
        }

        public async Task<Parameter> CreateAsync(string name, string code, ParameterTypeEnum type, string description = null, IsActiveEnum isActive = IsActiveEnum.Yes)
        {
            if (await _parameterRepository.CodeExistsAsync(code))
            {
                throw new UserFriendlyException("参数编码已存在！");
            }

            var parameter = new Parameter(GuidGenerator.Create(), name, code, type, description, isActive);
            await _parameterRepository.InsertAsync(parameter);
            return parameter;
        }

        public async Task ChangeNameAsync(Parameter parameter, string newName)
        {
            // 检查业务规则（如果需要）
            if (string.IsNullOrWhiteSpace(newName))
            {
                throw new UserFriendlyException("参数名称不能为空！");
            }

            parameter.Name = newName;
            await _parameterRepository.UpdateAsync(parameter);
        }

        public async Task ChangeCodeAsync(Parameter parameter, string newCode)
        {
            // 检查业务规则：新编码是否已存在（排除当前参数）
            if (await _parameterRepository.CodeExistsAsync(newCode, parameter.Id))
            {
                throw new UserFriendlyException("参数编码已存在！");
            }

            if (string.IsNullOrWhiteSpace(newCode))
            {
                throw new UserFriendlyException("参数编码不能为空！");
            }

            parameter.Code = newCode;
            await _parameterRepository.UpdateAsync(parameter);
        }

        public async Task ChangeActiveStatusAsync(Parameter parameter, IsActiveEnum isActive)
        {
            parameter.IsActive = isActive;
            await _parameterRepository.UpdateAsync(parameter);
        }
    }
}